#!/bin/sh /etc/rc.common
#
# Copyright (C) 2021-2025  sirpdboy  <herboy2008@gmail.com> https://github.com/sirpdboy/luci-app-lucky

# This file is part of lucky .
#
# This is free software, licensed under the Apache License, Version 2.0 .

START=99
STOP=15
USE_PROCD=1

CONF=lucky
PROG=/usr/bin/lucky
CONFDIR=/etc/lucky

get_config() {
  config_get_bool enabled $1 enabled 0
  config_get_bool logger $1 logger 1
  config_get port $1 port 16601
  config_get SafeURL $1 safe
  config_get delay $1 delay 0

}

init_config(){
	config_load "$CONF"
	config_foreach get_config "$CONF"
}

init_confdir(){
	[ -d $CONFDIR ] || mkdir -p $CONFDIR 2>/dev/null
}

LOG(){
   echo "$1"
   logger -t lucky -p warn "$1"
}

start_instance() {
    enabled=$(uci -q get $CONF.$CONF.enabled ) || enabled="0"
    logger=$(uci -q get $CONF.$CONF.logger ) || logger="1"
    port=$(uci -q get $CONF.$CONF.port ) || port="16601"
    SafeURL=$(uci -q get $CONF.$CONF.safe ) || SafeURL=" "
    delay=$(uci -q get $CONF.$CONF.delay ) || delay="5"
    SafeURL="${SafeURL##*( )}"
    SafeURL="${SafeURL%%*( )}"
    
    init_confdir
    [  x$enabled = x1 ] || return 1
    [ $(awk -F. '{print $1}' /proc/uptime) -lt "120" ] && sleep $delay 
    $(which lucky) -setconf -key AdminWebListenPort -value $port -cd $CONFDIR
    if [ -z "$SafeURL" ] ; then
        $(which lucky) -rCancelSafeURL
    else
        $(which lucky) -setconf -key SafeURL -value "$SafeURL" -cd $CONFDIR
    fi
    
    procd_open_instance
    procd_set_param command $PROG 
    procd_append_param command -cd $CONFDIR
    procd_set_param respawn
    procd_set_param stderr 1
    procd_close_instance
    LOG "lucky is start."

}

start_service() {
  pgrep -f $PROG | xargs kill -9 >/dev/null 2>&1
  start_instance
}

stop_service() {
  pgrep -f $PROG | xargs kill -9 >/dev/null 2>&1
  LOG "lucky is stop."
}

service_triggers() {
	procd_add_reload_trigger lucky
}
